package RestaurantManagement;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.HashMap;

public class RestaurantService {
    private HashMap<String, Ingredient> ingredients;
    HashMap<String, Meal> meals;
    HashMap<String, HashMap<String, Integer>> orders;

    public RestaurantService() {
        ingredients = new HashMap<>();
        meals = new HashMap<>();
        orders = new HashMap<>();
    }

    public void addIngredient(String name, double price) {
        ingredients.put(name, new Ingredient(name, price));
    }

    public void createMeal(String name, ArrayList<String> ingredientNames) {

        if (name == null || name.trim().isEmpty()) {
            throw new IllegalArgumentException("Invalid meal name or ingredients.");
        }


        if (ingredientNames == null || ingredientNames.isEmpty()) {
            throw new IllegalArgumentException("Invalid meal name or ingredients.");
        }

        ArrayList<Ingredient> mealIngredients = new ArrayList<>();
        for (String ingredientName : ingredientNames) {
            Ingredient ingredient = ingredients.get(ingredientName);
            if (ingredient == null) {

                throw new IllegalArgumentException("Ingredient " + ingredientName + " not found.");
            }
            mealIngredients.add(ingredient);
        }


        meals.put(name, new Meal(name, mealIngredients));
    }

    public String placeOrder(HashMap<String, Integer> orderDetails) {
        String orderId = "ORDER_" + (orders.size() + 1);
        orders.put(orderId, orderDetails);
        return orderId;
    }

    public double calculateBill(String orderId) {
        HashMap<String, Integer> order = orders.get(orderId);
        double total = 0.0;
        if (order != null) {
            for (String mealName : order.keySet()) {
                Meal meal = meals.get(mealName);
                if (meal != null) {
                    total += meal.getPrice() * order.get(mealName);
                }
            }
        }
        return total;
    }

    public JPanel createMainPanel() {
        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createTitledBorder("Restaurant Management"));

        // Input panel
        JPanel inputPanel = new JPanel(new GridLayout(4, 2, 10, 10));
        JTextField ingredientNameField = new JTextField(10);
        JTextField ingredientPriceField = new JTextField(10);
        JTextField mealNameField = new JTextField(10);
        JTextField mealIngredientsField = new JTextField(10);
        inputPanel.add(new JLabel("Ingredient Name:"));
        inputPanel.add(ingredientNameField);
        inputPanel.add(new JLabel("Ingredient Price (RMB):"));
        inputPanel.add(ingredientPriceField);
        inputPanel.add(new JLabel("Meal Name:"));
        inputPanel.add(mealNameField);
        inputPanel.add(new JLabel("Ingredients (comma-separated):"));
        inputPanel.add(mealIngredientsField);

        // Button panel
        JPanel buttonPanel = new JPanel(new FlowLayout());
        JButton addIngredientButton = new JButton("Add Ingredient");
        JButton createMealButton = new JButton("Create Meal");
        JButton placeOrderButton = new JButton("Place Order");
        buttonPanel.add(addIngredientButton);
        buttonPanel.add(createMealButton);
        buttonPanel.add(placeOrderButton);

        // Output area
        JTextArea outputArea = new JTextArea(10, 40);
        outputArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(outputArea);

        // Action listeners
        addIngredientButton.addActionListener(e -> {
            try {
                String name = ingredientNameField.getText().trim();
                double price = Double.parseDouble(ingredientPriceField.getText().trim());
                if (name.isEmpty() || price <= 0) {
                    throw new IllegalArgumentException("Invalid ingredient name or price.");
                }
                addIngredient(name, price);
                outputArea.append("Added ingredient: " + name + " (RMB " + price + ")\n");
                ingredientNameField.setText("");
                ingredientPriceField.setText("");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(panel, "Error adding ingredient: " + ex.getMessage());
            }
        });

        createMealButton.addActionListener(e -> {
            try {
                String mealName = mealNameField.getText().trim();
                String[] ingredients = mealIngredientsField.getText().trim().split(",");
                if (mealName.isEmpty() || ingredients.length == 0) {
                    throw new IllegalArgumentException("Invalid meal name or ingredients.");
                }
                ArrayList<String> ingredientList = new ArrayList<>();
                for (String ingredient : ingredients) {
                    String trimmed = ingredient.trim();
                    if (!trimmed.isEmpty()) {
                        ingredientList.add(trimmed);
                    }
                }
                if (ingredientList.isEmpty()) {
                    throw new IllegalArgumentException("No valid ingredients provided.");
                }
                createMeal(mealName, ingredientList);
                outputArea.append("Created meal: " + mealName + "\n");
                mealNameField.setText("");
                mealIngredientsField.setText("");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(panel, "Error creating meal: " + ex.getMessage());
            }
        });

        placeOrderButton.addActionListener(e -> {
            try {
                String mealName = JOptionPane.showInputDialog(panel, "Enter meal name to order:");
                if (mealName == null || mealName.trim().isEmpty()) {
                    throw new IllegalArgumentException("Meal name cannot be empty.");
                }
                int quantity;
                try {
                    quantity = Integer.parseInt(JOptionPane.showInputDialog(panel, "Enter quantity:"));
                    if (quantity <= 0) {
                        throw new IllegalArgumentException("Quantity must be positive.");
                    }
                } catch (NumberFormatException ex) {
                    throw new IllegalArgumentException("Invalid quantity.");
                }
                HashMap<String, Integer> order = new HashMap<>();
                order.put(mealName, quantity);
                String orderId = placeOrder(order);
                double bill = calculateBill(orderId);
                outputArea.append("Order placed: " + orderId + ", Bill: RMB " + bill + "\n");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(panel, "Error placing order: " + ex.getMessage());
            }
        });

        panel.add(inputPanel, BorderLayout.NORTH);
        panel.add(scrollPane, BorderLayout.CENTER);
        panel.add(buttonPanel, BorderLayout.SOUTH);
        return panel;
    }

    public JPanel getMainPanel() {
        return createMainPanel();
    }
}